package com.sun.dao.query.queryElement;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

public class SimpleElement implements ConditionElement {
	private static final long serialVersionUID = -4962251102860943816L;
	private String name;
	private boolean isEquals = true;
	private Boolean isLike;
	private Object value;

	public SimpleElement() {
	}

	public SimpleElement(String name, boolean isEquals, Object value) {
		this.name = name;
		this.isEquals = isEquals;
		this.value = value;
	}

	public SimpleElement(String name, boolean isEquals, Boolean isLike, Object value) {
		super();
		this.name = name;
		this.isEquals = isEquals;
		this.isLike = isLike;
		this.value = value;
	}

	public SimpleElement(String name, boolean isEquals, Object[] value) {
		this(name, isEquals, (Object) value);
	}

	public SimpleElement(String name, boolean isEquals, Collection<Object> value) {
		this(name, isEquals, (Object) value);
	}

	@Override
	public Criterion getCriterion() {
		Criterion criterion = null;
		if (this.getValue() == null) {
			criterion = Restrictions.isNull(this.getName());
		} else if (this.getValue() instanceof Collection) {
			Collection<?> vals = (Collection<?>) this.getValue();
			if (vals != null && vals.size() > 0) {
				criterion = Restrictions.in(this.getName(), vals);
			}
		} else if (this.getValue() instanceof Object[]) {
			Object[] vals = (Object[]) this.getValue();
			if (vals != null && vals.length > 0) {
				criterion = Restrictions.in(this.getName(), vals);
			}
		} else if (this.isLike() != null) {
			Criterion express = Restrictions.ilike(this.getName(), (String) this.getValue(), MatchMode.ANYWHERE);
			criterion = this.isLike() ? express : Restrictions.not(express);
		} else {
			criterion = Restrictions.eq(this.getName(), this.getValue());
		}
		if (!this.isEquals()) {
			criterion = Restrictions.not(criterion);
		}
		return criterion;
	}

	@Override
	public Criterion getCriterion(Class<?> entityCls) {
		return null;
	}

	private String getAlias() {
		if (StringUtils.indexOf(getName(), '.') != -1) {
			return StringUtils.substringBefore(getName(), ".");
		}
		return null;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean isEquals() {
		return isEquals;
	}

	public void setEquals(boolean isEquals) {
		this.isEquals = isEquals;
	}

	public Boolean isLike() {
		return isLike;
	}

	public void setIsLike(Boolean isLike) {
		this.isLike = isLike;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}

}
